<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\api\controller\wechat;

use app\common\model\MemberMiniapp;
use app\manage\model\Token;
use buwang\base\BaseController;
use buwang\facade\WechatMp;
use app\common\model\Member;
use buwang\service\UserService;
use Exception;
use think\facade\Cookie;

/**
 *  发起微信授权
 */
class WechatAccount extends BaseController
{
    /**
     * @var null
     */
    protected $bw_app = null;
    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $scan = bw_config('scan');
        if($scan && !$scan['qrcode_login']) return $this->error('二维码登录注册通道关闭');
        if($scan && !$scan['mp_id']) return $this->error('扫码登录公众号APPID未配置');
        $this->bw_app = MemberMiniapp::where('mp_appid',$scan['mp_id'])->field('id,mp_appid')->find();
    }

    /**
     *  生成登录二维码
     */
    public function createScanCode()
    {
        try {
            if(!$this->bw_app) {
                $wechat =WechatMp::official();
                if(!$wechat) return $this->error('请先完善扫码登录配置');
                $rel = $wechat->qrcode->temporary('scan_login', 6 * 24 * 3600);
            }else{
                $rel = WechatMp::getWechatObj($this->bw_app['id'])->qrcode->temporary('scan_login', 6 * 24 * 3600);//配置的公众号对接过应用的情况
            }
            Cookie::set('login_ticket', $rel['ticket'], $rel['expire_seconds']);  //记录二维码ticket
            return $this->success('成功', ['url' => $rel['url']]);
        } catch (Exception $e) {
            return $this->error("错误信息:".$e->getMessage());
        }
    }

    /**
     *检查登录状态
     */
    public function getLoginState()
    {
        if (Cookie::has('login_ticket')) {
            $ticket = Cookie::get('login_ticket');
            $member = Member::where(['ticket' => $ticket])->field('id,username,openid,ticket')->find();
            if ($member) {
                $member->ticket = null;  //Ticket
                $member->save();
                //登录处理
                $rs = UserService::loginMember($member, true);
                if (!$rs['rs']) return $this->error($rs['error']);
                $rs['rs']['session_id'] = get_session_id();
                $rs['rs']['url'] = '/manage/member/index';
                Cookie::delete('login_ticket');
                return $this->success('成功', $rs['rs'], 400200);
            }
        }
        return $this->error('尚未登录');
    }

    /**
     *租户扫码登录绑定Openid
     */
    public function bindQrcodeOpenid(){
        $code = $this->request->param('code');
        $token = $this->request->param('token/s');

        try {
            $jwtInfo = self::decodeToken($token);//解析token,获取用户信息
            if($jwtInfo){
                //应用类型 mini_program app h5 official pc system
                $scopes = $jwtInfo->scopes;
                if($scopes != 'member') return $this->error_jump('token解析失败！',NOT_JUMP);
                //redis验证
                $user = Token::validateRedisToken($token, $jwtInfo);
                $err_msg = Token::getError("未登录，请先去登录");
                if(!$user) return $this->error_jump($err_msg,NOT_JUMP);
            }

            if(!$this->bw_app) $official = WechatMp::official();
            else $official = WechatMp::getWechatObj($this->bw_app['id']);//配置的公众号对接过应用的情况
            if (!$official) {
                return $this->error_jump('扫码登录公众号配置不正确！',NOT_JUMP);
            }

            if (!empty($code)) {
                $memberOpenid = $official->oauth->userFromCode($code)->getID();//对应微信的 openid
                if($user['openid']) return $this->error_jump('已经绑定过，请勿重复绑定！！请刷新页面再试！',NOT_JUMP);
                $user->openid = $memberOpenid;
                if(!$user->save()) return $this->error_jump('绑定微信失败',NOT_JUMP);;
                return $this->renderHtml('恭喜您，绑定微信成功！', '请关闭当前网页，下次可直接【电脑端扫码登录账号】。');

            }

            $redirectUrl = $official->oauth->scopes(['snsapi_userinfo'])->redirect((string)url('api/official/bindQrcodeOpenid', ['token'=>$token], false, true));
            return redirect($redirectUrl);
        } catch (Exception $e) {
            return $this->error_jump($e->getMessage(),NOT_JUMP);
        }
    }
    /**
     * 渲染简洁提示页面
     *
     * @param string $title 页面标题
     * @param string $message 提示信息
     * @param string $linkText 链接文字
     * @param string $linkUrl 链接地址
     */
    protected function renderHtml(string $title, string $message)
    {
        $html = <<<HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{$title}</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f5f7fa;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 90%;
            text-align: center;
        }
        h2 {
            color: #1890ff;
        }
        p {
            margin: 20px 0;
            color: #666;
        }
        a.button {
            display: inline-block;
            padding: 10px 20px;
            background-color: #1890ff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>{$title}</h2>
    <p>{$message}</p>
</div>
</body>
</html>
HTML;

        return response($html)->contentType('text/html');
    }

}